//用户行为记录
var userRecode = function (opt) {

    //设置mediaSources
    var usrMediaSources = getUrlPara('mediasources');
    if(usrMediaSources){
        $.cookie('mediasources', usrMediaSources);
    }

    var options = {
        category1: window.cateData.pageIndustryName,
        category2: '',
        title: window.cateData.pageIndustryName + '行业',
        module: '行业模块',
        tag: '',
        enterpriseName: '', //页面入口
        cookieId: $.cookie('globalUserId'),
        equipment: client.browseInfo.equipment,
        browser: client.browseInfo.browser,
        platform: client.browseInfo.os,
        linkSource: document.referrer,
        url: location.href,
        behaviorResult: '浏览成功',
        behaviorType: '浏览网页',
        // behaviorCreatTime: '',//后端生成
        mediaSources: $.cookie('mediasources'),
        ip: client.ip,
    };

    //根据不同模块设置不同的配置
    if (window.cateData.pageModule === 'industry') { //行业
        options.category1 = window.cateData.pageIndustryName;
        options.title = window.cateData.pageIndustryName;
        options.module = '行业模块';
    } else if (window.cateData.pageModule === 'tank') { //案例智库
        options.category1 = window.cateData.userRecodeOption.category1;
        options.title = '案例智库';
        options.module = '案例智库';
        options.tag = window.cateData.userRecodeOption.tag;
    } else if (window.cateData.pageModule === 'program') { //解决方案
        options.category1 = window.cateData.userRecodeOption.category1;
        options.title = window.cateData.userRecodeOption.title;
        options.module = '解决方案';
        options.tag = window.cateData.userRecodeOption.tag;
    } else if (window.cateData.pageModule === 'index') {//首页
        options.category1 = '';
        options.title = '首页';
        options.module = '首页';
    } else if (window.cateData.pageModule === 'detail') {//文章详情
        options.category1 = window.cateData.userRecodeOption.category1;
        options.category2 = window.cateData.userRecodeOption.category2;
        options.title = window.cateData.userRecodeOption.title;
        options.module = window.cateData.userRecodeOption.module;
        options.tag = window.cateData.userRecodeOption.tag;
        options.behaviorResult = window.cateData.userRecodeOption.title;
        options.behaviorType = '阅读文章';
    } else if (window.cateData.pageModule === 'light-reading') {//轻阅读
        options.category1 = window.cateData.userRecodeOption.category1;
        options.category2 = window.cateData.userRecodeOption.category2;
        options.title = window.cateData.userRecodeOption.title;
        options.module = window.cateData.userRecodeOption.module;
    } else if (window.cateData.pageModule === 'filelist') { //资料中心
        options.category1 = window.cateData.userRecodeOption.category1;
        options.title = window.cateData.userRecodeOption.title;
        options.module = window.cateData.userRecodeOption.module;
    }else{
        options.category1 = window.cateData.userRecodeOption.category1;
        options.category2 = window.cateData.userRecodeOption.category2;
        options.title = window.cateData.userRecodeOption.title;
        options.module = window.cateData.userRecodeOption.module;
        options.tag = window.cateData.userRecodeOption.tag;
        options.behaviorType = window.cateData.userRecodeOption.behaviorType;
        options.behaviorResult = window.cateData.userRecodeOption.behaviorResult;
    }

    //继承方法
    var extend = function (destination, source) {
        if (!source) {
            return destination;
        }
        for (var property in source) {
            destination[property] = source[property];
        }
        return destination;
    };

    var parsOptions = extend(options, getUserInfo.options);
    parsOptions = extend(options, opt);

    var url = window.cateData.userActionUrl;

    try {
        var gioParams = {
            module_pvar: parsOptions.module? parsOptions.module : '',
            category1_pvar: parsOptions.category1? parsOptions.category1 : '',
            category2_pvar: parsOptions.category2? parsOptions.category2 : '',
            category3_pvar: parsOptions.category3? parsOptions.category3 : '',
            title_pvar: parsOptions.title? parsOptions.title : '',
            url_pvar: parsOptions.url? parsOptions.url : '',
            mediaSources_pvar: parsOptions.mediaSources? parsOptions.mediaSources : '',
            linkSource_pvar: parsOptions.linkSource? parsOptions.linkSource : '',
            behaviorType_pvar: parsOptions.behaviorType? parsOptions.behaviorType : '',
            behaviorResult_pvar: parsOptions.behaviorResult? parsOptions.behaviorResult : '',

            linkSourceModule_pvar: getCookie('linkSourceModule_pvar') || '', //页面来源栏目模块（行为数据)
            linkSourceCategory1_pvar: getCookie('linkSourceCategory1_pvar') || '', //页面来源二级分类（行为数据）
            linkSourceTitle_pvar: getCookie('linkSourceTitle_pvar') || '', //页面来源title（行为数据）
        }
        // console.log(gioParams);
        gio('page.set', gioParams);
        gio('evar.set', {'moduleName_last_evar': gioParams.module_pvar, 'moduleName_linear_evar':gioParams.module_pvar});
        gio('evar.set', {'category1_last_evar': gioParams.category1_pvar, 'category1_linear_evar':gioParams.category1_pvar});
        gio('evar.set', {'title_linear_evar': document.title, 'title_last_evar':document.title});
        setCookie('linkSourceModule_pvar', gioParams.module_pvar);
        setCookie('linkSourceCategory1_pvar', gioParams.category1_pvar);
        setCookie('linkSourceTitle_pvar', gioParams.title_pvar);
    }catch (e) {
        // console.log('pc userRecode js gio error',e);
    }

    postJson(url, parsOptions, function (data) {

    });

    /*$.ajax({
        type: "POST",
        url: url,
        data: parsOptions,
        dataType: "json",
        success: function (data) {
        }
    });*/
};

// 用户信息获取
var getUserInfo = {
    options: {
        globalUserId: '',
        cookieId: '',
        userId: '',
        openId: '',
        unionId: '',
        email: '',
        mobile: '',
        name: '',
        areaCode: '',
        companyPhone: '',
        extension: '',
        enterpriseName: '',
        department: '',
        position: '',
        province: '',
        address: '',
        industry: '',
        companyNum: '',
        ifWish: '',
        privacyNotice: '',
    },
    //获取globalUserId
    globalUserId: function () {
        var _this = this;
        var globalUserId = getCookie('globalUserId');
        var info = {
            clientBrand: '',
            clientIP: client.ip || '',
            clientType: '',
            clientVersion: '',
        }
        if (!globalUserId) {
            var getUrl = window.cateData.api.getGlobalUserId;
            postJson(getUrl, info, function (data) {
                setCookie('globalUserId', data.body.content);
                setOption();
                _this.getUserId();
            });
        } else {
            setOption();
            _this.getUserId();
        }

        function setOption() {
            _this.options.globalUserId = getCookie('globalUserId');
        }
    },

    //获取用户ID
    getUserId: function () {
        var _this = this;

        try {
            _this.options.globalUserId = _this.options.globalUserId.replace(/"/g, ""); //去除字符串中的双引号
            gio('visitor.set', {'cookieID':_this.options.globalUserId }); //GIO 访问用户变量上传
        }catch (e) {
            
        }


        if (!isLogin()) {
            _this.options = {globalUserId: _this.options.globalUserId}
            userRecode(_this.options);
            //构子函数
            getUserInfoDone(false);
            return;
        }

        var info = {
            tenantId: window.cateData.tenantId,
            sess: isLogin().session || '',
        };
        var getUrl = window.cateData.api.getUserId;

        postJson(getUrl, info, function (data) {
            var ids = data.body.content;

            _this.options.cookieId = ids["cookieId"] ? ids["cookieId"] : '';
            _this.options.userId = ids["loginId"] ? ids["loginId"] : '';
            _this.options.openId = ids["openId"] ? ids["openId"] : '';
            _this.options.unionId = ids["unionId"] ? ids["unionId"] : '';
            _this.getUserInfo();
        });
    },

    //获取用户信息
    getUserInfo: function () {
        var _this = this;
        var info = {
            globalUserId: getCookie('globalUserId') || '',
            sess: isLogin().session || '',
        };

        var getUrl = window.cateData.api.getUserInfo;
        postJson(getUrl, info, function (data) {

            if (data.body.result === 0) {
                var d2_rs = {};
                data.body.content.forEach(function (item) {
                    d2_rs[item.key] = item.value;
                });
                _this.options.email = d2_rs["email"] ? d2_rs["email"] : '';
                _this.options.mobile = d2_rs["mobile"] ? d2_rs["mobile"] : '';
                _this.options.name = d2_rs["name"] ? d2_rs["name"] : '';
                _this.options.areaCode = d2_rs["areacode"] ? d2_rs["areacode"] : '';
                _this.options.companyPhone = d2_rs["compphone"] ? d2_rs["compphone"] : '';
                _this.options.extension = d2_rs["ext"] ? d2_rs["ext"] : '';
                _this.options.enterpriseName = d2_rs["enterprise_name"] ? d2_rs["enterprise_name"] : '';
                _this.options.department = d2_rs["department"] ? d2_rs["department"].toString() : "";
                _this.options.position = d2_rs["position"] ? d2_rs["position"].toString() : "";
                _this.options.province = d2_rs['province'] ? d2_rs['province'].toString() : '';
                _this.options.address = d2_rs['address'] ? d2_rs['address'] : '';
                _this.options.industry = d2_rs['industry'] ? d2_rs['industry'].toString() : '';
                _this.options.companyNum = d2_rs['employeesNumber'] ? d2_rs['employeesNumber'].toString() : '';
                _this.options.ifWish = d2_rs['ifWish'] ? d2_rs['ifWish'].toString() : '';
                _this.options.privacyNotice = d2_rs['privacynotice'] ? d2_rs['privacynotice'].toString() : '';
                userRecode(_this.options);

                //构子函数
                getUserInfoDone(true);
                //gio触发
                gio('setUserId', _this.options.userId);
                var gioParams = {
                    userName_ppl: _this.options.name,
                    companyName_ppl: _this.options.enterpriseName,
                    industry_ppl: _this.options.industry,
                    companyScale_ppl: _this.options.companyNum,
                    userRole_ppl: _this.options.position,
                    area_ppl: _this.options.province,
                    email_ppl: _this.options.email,
                    phone_ppl: _this.options.mobile,
                };
                gio('people.set',gioParams);
            } else {
                // 用户认证失败删除相应cookie
                delCookie('smarketMember_' + window.cateData.schemaId);
                delCookie('globalUserId');
                //构子函数
                getUserInfoDone(false);
                userRecode(_this.options);
            }
        })
    },

    init: function () {
        //获取globalUserId
        this.globalUserId();
    }
}


//客户端信息获取
var client = {
    ip: '',
    browser: {
        version: '',
        name: '',
    },
    browseInfo: {
        userAgent: '',
        browser: '',
        version: '',
        os: '',
        equipment: '',
        resolution: '',
        referenceUrl: '',
        referenceTitle: '',
    },
    os: {
        name: '',
    },
    screen: {
        width: window.screen.width,
        height: window.screen.height,
        resolution: window.screen.width + ' * ' + window.screen.height,
    },

    getBrowseInfo: function () {
        var ua, liulanqi, banben, os, equipment, isEdge, isSafari, isChrome, isFirefox, isOpera, isIE, isBrowser,
            isAndroid, isWe, isIPhones, isIPad, isVersion, isWeChat;
        ua = navigator.userAgent;
        liulanqi = '';
        banben = '';
        os = '';
        equipment = '';
        isEdge = ua.match(/(Edge)\/([\d.]+)/i);
        isSafari = ua.match(/Version\/([\d.]+)\s+?(Safari)/i);
        isChrome = ua.match(/(Chrome)\/([\d.]+)/i);
        isFirefox = ua.match(/(Firefox)\/([\d.]+)/i);
        isOpera = ua.match(/(OPR|OPERA).+?([\d.]+)/i);
        isIE = ua.indexOf('Trident') > -1 ||
            ua.toLocaleLowerCase().indexOf('msie') > -1;
        isBrowser = ua.match(/(\w+Browser)[^\d]+?([\d.]+)/i) ||
            ua.match(/\d\s+?([^\d]+)([\d.]+)$/i);
        isAndroid = ua.match(/(Android[\s\d.]+);.+?([^;]+)Build/i);
        isWe = ua.match(/MicroMessenger.+?([\d.]+)/i);
        isIPhones = ua.match(/CPU([\s\w\d_]+)like/i);
        isIPad = ua.match(/iPad/i) ? 'iPad' : 'iPhone';
        isVersion = ua.match(/Version\/([\d.]+)/i);
        isWeChat = isWe;

        //如果是移动端
        if (!!ua.match(/AppleWebKit.*Mobile.*/)) {
            if (isWe) {
                liulanqi = '微信';
                banben = isWe[1];
            } else {
                if (isBrowser) {
                    liulanqi = isBrowser[1];
                    banben = isBrowser[2];
                    if (liulanqi.indexOf('Browser') === -1 && isVersion) {
                        banben = isVersion[1];
                    }
                } else {
                    liulanqi = '手持设备浏览器';
                    banben = '未知';
                }
            }
            if (isAndroid) {
                os = isAndroid[1];
                equipment = isAndroid[2];
            } else {
                if (isIPhones) {
                    os = isIPhones[1];
                } else {
                    os = isIPad;
                }
                equipment = isIPad;
            }
        } else {
            if (isSafari) {
                liulanqi = isSafari[2];
                banben = isSafari[1];
            }
            if (isChrome) {
                liulanqi = isChrome[1];
                banben = isChrome[2];
            }
            if (isFirefox) {
                liulanqi = isFirefox[1];
                banben = isFirefox[2];
            }
            if (isEdge) {
                liulanqi = isEdge[1];
                banben = isEdge[2];
            }
            if (isOpera) {
                liulanqi = 'OPERA';
                banben = isOpera[2];
            }

            if (isIE) {
                liulanqi = 'IE';
                var isIEV01 = ua.match(/(MSIE).+?(\d+)/i);
                var isIEV02 = ua.match(/(rv).+?(\d+)/i);
                if (isIEV01) {
                    banben = isIEV01[2];
                }
                if (isIEV02) {
                    banben = isIEV02[2];
                }
            }
            os = ua.match(/windows/i) ? 'Windows' : 'Mac OS';
            equipment = '电脑端';
        }
        this.browseInfo.userAgent = ua;
        this.browseInfo.browser = liulanqi;
        this.browseInfo.version = banben;
        this.browseInfo.os = os;
        this.browseInfo.equipment = equipment;
        this.browseInfo.resolution = window.screen.width + 'X' + window.screen.height;
        this.browseInfo.referenceUrl = document.referrer || '';
        this.browseInfo.referenceTitle = '';
    },

    getIp: function () {
        var _this = this;
        // $.getScript('//pv.sohu.com/cityjson?ie=utf-8').done(function (data) {
        //     _this.ip = returnCitySN.cip;
        //     getUserInfo.init();
        // });
    },

    init: function () {
        this.getIp();
        this.getBrowseInfo();
    }
};